﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using MyGeneration.dOOdads;

namespace WebUI.Controls
{
    public partial class PurchaseOrderCtrl : BaseEditControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            if (!IsPostBack)
            {
                Suppliers sup = Suppliers.GetAllActiveSuppliers();
                Utilities.LoadDropDownList(ddlSupplier, sup.DefaultView, Suppliers.ColumnNames.SupplierName, Suppliers.ColumnNames.ID);

                PaymentMethod methods = PaymentMethod.GetAllMethods();
                Utilities.LoadDropDownListNoSelect(ddlPaymentMethod, methods.DefaultView, PaymentMethod.ColumnNames.Name, PaymentMethod.ColumnNames.ID);
                methods.Filter = PaymentMethod.ColumnNames.Default + "=1 and " + PaymentMethod.ColumnNames.MethodType + "='P'";
                if (methods.RowCount > 0)
                    ddlPaymentMethod.SelectedValue = methods.ID.ToString();

                txtDate.Text = DateTime.UtcNow.AddHours(SysVars.TimeZone).ToString(SysVars.DateFormat);
                lblUser.Text = SessionUser.s_FullName;
                NewPurchaseOrder();
            }
        }

        protected void btnEditProd_Click(Object sender, EventArgs e)
        {
            purchaseOrderDetails.UpdateTotalAmt();
            purchaseOrderDetails.Refresh();
            txtTotalAmt.Text = string.Format("{0:C}", purchaseOrderDetails.TotalAmt);

            updateGrid.Update();
            updateTotalLabel.Update();
        }

        protected void btnRemoveProd_Click(object sender, EventArgs e)
        {
            purchaseOrderDetails.DeleteCheckedItems();
            txtTotalAmt.Text = string.Format("{0:C}", purchaseOrderDetails.TotalAmt);

            purchaseOrderDetails.Refresh();
            updateGrid.Update();
            updateTotalLabel.Update();
        }

        protected void btnSubmit_OnClick(object sender, EventArgs e)
        {
            if (purchaseOrderDetails == null || purchaseOrderDetails.TotalAmt == 0)
            {
                ShowErrorMessage(mainPanel, "(*)Nothing to purchase!");
                return;
            }

            if (PurchaseOrders.IsPurchaseNoExisted(txtPurchaseOrderNo.Text))
            {
                ShowErrorMessage(mainPanel, "(*)Purchase order " + txtPurchaseOrderNo.Text + " has already existed!");
                return;
            }

            TransactionMgr tx = TransactionMgr.ThreadTransactionMgr();
            try
            {
                tx.BeginTransaction();

                //create P.O
                PurchaseOrders po = new PurchaseOrders();
                po.AddNew();
                po.BranchID = Branches.CurrentBranchID;
                po.Deleted = false;
                po.CreatedByUser = SessionUser.ID;
                po.CreatedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                po.LastModifiedByUser = SessionUser.ID;
                po.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                po.InvoiceNo = txtInvoiceNo.Text;
                po.PurchaseOrderNo = txtPurchaseOrderNo.Text;
                po.GSTTotalAmount = purchaseOrderDetails.TotalGST;
                po.TotalAmount = purchaseOrderDetails.TotalAmt;
                if (txtPayAmt.Text != "")
                    po.PaidAmount = Decimal.Parse(txtPayAmt.Text);
                else
                    po.PaidAmount = 0;

                po.SupplierID = int.Parse(ddlSupplier.SelectedValue);
                po.Save();

                Suppliers sup = new Suppliers();
                sup.UpdateSupllierAmt(po.SupplierID, po.TotalAmount, po.PaidAmount);
                //insert a row into PurchasePaymentHistories
                if (po.PaidAmount > 0)
                {
                    PurchasePaymentHistories.AddNewPayment(po.ID, int.Parse(ddlPaymentMethod.SelectedValue), po.PaidAmount);
                }
                //Add PurchaseOrderDetails
                purchaseOrderDetails.Filter = "";
                purchaseOrderDetails.OrderItems.Rewind();
                PurchaseOrderDetails poDetails = new PurchaseOrderDetails();
                ProductDetails prodDetails = new ProductDetails();

                purchaseOrderDetails.OrderItems.Rewind();
                for (int i = 0; i < purchaseOrderDetails.OrderItems.RowCount; i++)
                {

                    poDetails.AddNew();
                    poDetails.BranchID = Branches.CurrentBranchID;
                    poDetails.AddInfoPlus(po.ID, purchaseOrderDetails.OrderItems.ProductID, purchaseOrderDetails.OrderItems.IMEI,
                        purchaseOrderDetails.OrderItems.Description, purchaseOrderDetails.OrderItems.Quantity, purchaseOrderDetails.OrderItems.UnitPrice, purchaseOrderDetails.OrderItems.GST);
                    poDetails.LastModifiedByUser = SessionUser.ID;
                    poDetails.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);

                    if (!String.IsNullOrEmpty(purchaseOrderDetails.OrderItems.IMEI))
                    {
                        //add row into ProductDetails and ProductDetailHistories
                        prodDetails.AddNew();
                        prodDetails.AddInfo(purchaseOrderDetails.OrderItems.ProductID, "", purchaseOrderDetails.OrderItems.IMEI, po.SupplierID,
                            0, (int)ProductDetails.ProductStatus.Purchased);
                        prodDetails.LastModifiedByUser = SessionUser.ID;
                        prodDetails.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                    }

                    purchaseOrderDetails.OrderItems.MoveNext();
                }
                poDetails.Save();
                prodDetails.Save();

                //update product qty
                poDetails.Rewind();
                for (int i = 0; i < poDetails.RowCount; i++)
                {
                    if (String.IsNullOrEmpty(poDetails.IMEI))
                    {
                        //adjust qty, set product.qty += qty
                        string res = Products.UpdateProductQty(poDetails.ProductID, poDetails.Quantity);
                        if (!string.IsNullOrEmpty(res))
                            throw new Exception(res);
                    }
                    else
                        //adjust qty, set product.qty = sum(product details)
                        Products.SyncProductQty(poDetails.ProductID);
                    poDetails.MoveNext();
                }

                //history
                poDetails.Rewind();
                prodDetails.Rewind();
                ProductDetailHistories productHistory = new ProductDetailHistories();
                for (int i = 0; i < prodDetails.RowCount; i++)
                {
                    poDetails.Filter = "IMEI='" + prodDetails.IMEI + "'";

                    productHistory.AddNew();
                    productHistory.BranchID = Branches.CurrentBranchID;
                    productHistory.AddInfo(prodDetails.ID, (int)ProductDetails.ProductStatus.Purchased,
                        0,
                        String.Format("Purchased from {1}. Transfered to {2}. User: '{3}'. Cost: {0:C}", poDetails.UnitPrice, ddlSupplier.SelectedItem.Text, Branches.CurrentBranch.s_Name, SessionUser.s_FullName),
                        po.SupplierID, poDetails.UnitPrice);
                    productHistory.UserID = SessionUser.ID;

                    prodDetails.MoveNext();
                }

                productHistory.Save();

                tx.CommitTransaction();

                purchaseOrderDetails.Refresh();

                ShowHintMessage(mainPanel, "(*)Purchase Order has been submitted!");
                btnSubmit.Visible = false;
                btnPrint.Visible = true;
                hidNewPurchaseID.Value = po.ID.ToString();

                if (chkAutoPrint.Checked)
                    PrintPO();

            }
            catch (Exception ex)
            {
                tx.RollbackTransaction();
                ErrorLog.WriteToFile("PurchaseOrderCtrl.cs", "btnSubmit_Click", ex.StackTrace);
                ShowErrorMessage(mainPanel, "(*)Error: " + ex.Message);
            }
        }

        protected void btnNewPO_OnClick(object sender, EventArgs e)
        {
            NewPurchaseOrder();
        }

        private void NewPurchaseOrder()
        {
            Sequence seq = new Sequence();

            txtPurchaseOrderNo.Text = seq.GetNewID("PurchaseOrders");
            purchaseOrderDetails.TotalAmt = 0;
            purchaseOrderDetails.TotalGST = 0;
            purchaseOrderDetails.OrderItems = new PurchaseOrderDetails();
            purchaseOrderDetails.OrderItems.LoadByPrimaryKey(-1);
            txtPayAmt.Text = "0";
            txtInvoiceNo.Text = "";
            txtTotalAmt.Text = string.Format("{0:C}", purchaseOrderDetails.TotalAmt);

            btnSubmit.Visible = true;
            btnPrint.Visible = false;

            purchaseOrderDetails.Refresh();

            btnSubmit.Enabled = SessionUser.BranchID == Branches.CurrentBranchID;
        }

        public string GetOrderDetailsEditPageLink()
        {
            return this.ResolveUrl("~/EditPages/EditPurchaseDetails.aspx") + "?key=" + purchaseOrderDetails.SourceObjectSessionID;
        }

        public void AddProduct(int productID, int qty)
        {
            purchaseOrderDetails.AddNonIMEIProduct(productID, qty);
            txtTotalAmt.Text = string.Format("{0:C}", purchaseOrderDetails.TotalAmt);

            updateGrid.Update();
            updateTotalLabel.Update();
        }

        public void AddIMEIs(string[] imeis, int productID)
        {
            purchaseOrderDetails.AddIMEI(imeis, productID);
            txtTotalAmt.Text = string.Format("{0:C}", purchaseOrderDetails.TotalAmt);
            updateGrid.Update();
            updateTotalLabel.Update();
        }

        protected void btnPrint_OnClick(object sender, EventArgs e)
        {
            PrintPO();
        }

        private void PrintPO()
        {
            try
            {
                PurchaseViewerCtrl poViewer = (PurchaseViewerCtrl)LoadControl(@"~/Controls/POSControls/PurchaseViewerCtrl.ascx");
                if (hidNewPurchaseID.Value != "")
                    poViewer.LoadPurchaseByID(int.Parse(hidNewPurchaseID.Value));

                Session[PrintKey] = poViewer;
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showPrintDlg('{0}');", GetPrintPage()), true);
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("PurchaseOrderCtrl.ascx.cs", "PrintPO", ex.StackTrace);
            }
        }

        public string PrintKey
        {
            get
            {
                if (ViewState["PrintKey"] == null)
                    ViewState["PrintKey"] = Guid.NewGuid().ToString();
                return ViewState["PrintKey"].ToString();
            }
        }

        public string GetPrintPage()
        {
            return "EditPages/PrintHandler.aspx?key=" + PrintKey;
        }
    }
}